package com.dtp.core;

import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.ResolvableType;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotationMetadata;


/**
 * @author evolution
 * @title: DtpImportBeanDefinitions
 * @projectName dtp-nacos
 * @description: TODO
 * @date 2022-10-20 17:53
 */
public class DtpImportBeanDefinitions implements ImportBeanDefinitionRegistrar, EnvironmentAware {
    
    private Environment environment;
    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }
    
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        DtpProperties dtpProperties = new DtpProperties();
        Binder binder =Binder.get(environment);
        ResolvableType type= ResolvableType.forClass(DtpProperties.class);
        Bindable<?> target =Bindable.of(type).withExistingValue(dtpProperties);
        binder.bind("dtp",target);
        
        for(DtpProperties.DtpExecutorProperties executorProperties : dtpProperties.getExecutors()){
            AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition().getBeanDefinition();
            beanDefinition.setBeanClass(DtpExecutor.class);
            beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(executorProperties.getCorePoolSize());
            beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(executorProperties.getMaximumPoolSize());
            registry.registerBeanDefinition(executorProperties.getName(),beanDefinition);
        }
        
        
     }
    
 
}
